package VIEWS;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import CONTROLLERS.LuongControllers;
import CONTROLLERS.NhanVienControllers;
import CONTROLLERS.UsersControllers;
import ModelEntityFW.LuongEntity;
import ModelEntityFW.NhanVienEntity;
import ModelEntityFW.UserEntitys;
import Ultils.Controls;
import Ultils.FileIOStreams;

import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Luong extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private static Connection m_objConnection;
    private LuongControllers m_objLuongController;
    private static UserEntitys m_objSecurityContext;
    
    private DefaultTableModel objDTM;
    private static boolean bFlag = false;
    private LuongEntity m_LuongEntity;

	/**
	 * Launch the application.
	 */
	

	/**
	 * Create the frame.
	 */
	public Luong(Connection objConnection, UserEntitys objSecurity) {
		setResizable(false);
		m_objConnection = objConnection;
		m_objSecurityContext = objSecurity;
		m_LuongEntity = new LuongEntity();
		objDTM = new DefaultTableModel();
		m_objLuongController = new LuongControllers(m_objConnection, m_objSecurityContext);
		
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 834, 482);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 818, 49);
		contentPane.add(toolBar);
		
		JButton btnCapNhat = new JButton("Cập Nhật [!]");
		btnCapNhat.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(bFlag){
					m_LuongEntity.setMaNhanVien(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 0))));
					m_LuongEntity.setHoVaTen(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 1)));
					m_LuongEntity.setTrinhDo(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 2)));
					m_LuongEntity.setNgayLamViec(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 3)));
					m_LuongEntity.setLuongCoBan(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 4))));
					m_LuongEntity.setLuongThuongThem(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 5))));
					m_LuongEntity.setTongLuong(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 6))));
					
					Editluong frm=new Editluong(m_objConnection, m_objSecurityContext, m_LuongEntity);
					frm.setVisible(true);
					bFlag = false;
				}else{
					JOptionPane.showMessageDialog(getParent(), "Chưa chọn bản ghi cần thay đổi!!!", "Thông báo", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		btnCapNhat.setIcon(new ImageIcon(Luong.class.getResource("/images/editgv2.png")));
		btnCapNhat.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnCapNhat);
		
		JButton btnXoa = new JButton("Xóa[-]");
		btnXoa.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				if(bFlag){
					m_LuongEntity.setbFlag(bFlag);
					m_LuongEntity.setMaNhanVien(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 0))));
					boolean bResult = false;
					try {
						bResult = m_objLuongController.ExecOfDeleteElement(m_LuongEntity);
					} catch (Exception e2) {
						JOptionPane.showMessageDialog(getParent(), "Error: "+e2.getMessage(), "Thông Báo", JOptionPane.ERROR_MESSAGE);
						// TODO: handle exception
					}
					
					if(bResult){
						JOptionPane.showMessageDialog(getParent(), "Xóa thành công!!!", "Thông Báo", JOptionPane.INFORMATION_MESSAGE);
					}
					bFlag = false;
				}else
					JOptionPane.showMessageDialog(getParent(), "Chưa chọn thông tin!!!", "Thông Báo", JOptionPane.ERROR_MESSAGE);
				
			
				
			}
		});
		btnXoa.setIcon(new ImageIcon(Luong.class.getResource("/images/delete.gif")));
		btnXoa.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnXoa);
		
		JButton btnTimKiem = new JButton("Tìm Kiếm [=]");
		btnTimKiem.setIcon(new ImageIcon(Luong.class.getResource("/images/search.png")));
		btnTimKiem.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnTimKiem);
		
		JButton btnLamTuoi = new JButton("Làm Tươi [^]");
		btnLamTuoi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LoadData(true);
			}
		});
		btnLamTuoi.setIcon(new ImageIcon(Luong.class.getResource("/images/renew.png")));
		btnLamTuoi.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnLamTuoi);
		
		JButton btnGhiXuongFiles = new JButton("Ghi Xuống Files[*]");
		btnGhiXuongFiles.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] options = { "XML File", "JSON File","DAT File", "Hủy bỏ" };
                int n = JOptionPane.showOptionDialog(getParent(), "Hãy chọn loại File bạn muốn ghi: ",
                        "Chọn thể lại File", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[1]);
                if (n == 0) {
                	List<Object> listField = new ArrayList<Object>();
                	List<List<Object>> listValues = new ArrayList<List<Object>>();
                	List<Object> Values = new ArrayList<Object>();
                	try {
						ResultSet objRs = m_objLuongController.ExecOfGetElements();
						ResultSetMetaData objMeta = objRs.getMetaData();
						int col = objMeta.getColumnCount();
						
						for (int i = 1; i<=col; i++){
							listField.add(objMeta.getColumnName(i));
						}
						while(objRs.next()){
							Values = new ArrayList<Object>();
							for(int j = 1; j<=col; j++){
								Values.add(objRs.getString(j));
								
							}
							listValues.add(Values);
						}
					} catch (Exception e2) {
						// TODO: handle exception
					}
                	boolean bResult = false;

                    JFileChooser objFile = new JFileChooser();
                    objFile.setCurrentDirectory(new java.io.File("."));
                    objFile.setDialogTitle("Chọn file: ");
                    objFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                    String[] EXTENSION = new String[] { "xml" };
                    FileNameExtensionFilter filter = new FileNameExtensionFilter("XML files", EXTENSION);
                    objFile.setFileFilter(filter);
                    objFile.setMultiSelectionEnabled(false);

                    int returnVal = objFile.showSaveDialog(getParent());
                    String ParentPath = "";
                    String FileName = "";
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        ParentPath = objFile.getSelectedFile().getParent();
                        FileName = objFile.getSelectedFile().getName();
                    }
                    
                String Path = ParentPath+"/"+FileName+".xml";
                FileIOStreams<LuongEntity> objFileIO = new FileIOStreams<LuongEntity>();
                try {
					List<Object> lisField;
					bResult = objFileIO.WriteElements(listField, listValues, "PMQUANLYBENHVIEN", "Luong", Path, true);
					
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(getParent(), "Err: "+e1.getMessage());
					// TODO: handle exception
				}
                if(bResult){
                	JOptionPane.showMessageDialog(getParent(), "Ghi xuống file XML thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                }
                    
                } else if (n == 1) {
                    JOptionPane.showMessageDialog(getParent(), "Ghi xuống file JSON thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                }
                else if(n==2){
                	List<HashMap<String, String>> lisHash = new ArrayList<HashMap<String,String>>();
					HashMap<String, String> hashMap = null;
					
					ResultSet objRs = null;
					ResultSetMetaData objRsData = null;
					
					try {
						objRs = m_objLuongController.ExecOfGetElements();
						
						objRsData = objRs.getMetaData();
						
						int col = objRsData.getColumnCount();
						
						while(objRs.next()){
							hashMap = new HashMap<String, String>();
							for(int i=1; i<=col; i++){
								hashMap.put(objRsData.getColumnName(i), objRs.getString(i));
							}
							lisHash.add(hashMap);
						}
					} catch (Exception e2) {
						// TODO: handle exception
						e2.getMessage();
					}
					boolean bResult = false;
					
					JFileChooser objFile = new JFileChooser();
			        objFile.setCurrentDirectory(new java.io.File("."));
			        objFile.setDialogTitle("Lưu file: ");
			        objFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			        String[] EXTENSION = new String[] { "dat" };
			        FileNameExtensionFilter filter = new FileNameExtensionFilter("DAT files", EXTENSION);
			        objFile.setFileFilter(filter);
			        objFile.setMultiSelectionEnabled(false);

			        int returnVal = objFile.showSaveDialog(null);
			        String ParentPath = "";
			        String FileName = "";
			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            ParentPath = objFile.getSelectedFile().getParent();
			            FileName = objFile.getSelectedFile().getName();
			            String resource = ParentPath+"/";
			            String fileName = FileName+".dat";
			            FileIOStreams<List<HashMap<String, String>>> objFileIo = new FileIOStreams<List<HashMap<String, String>>>();
			            try {
							bResult = objFileIo.WriteListObjects(lisHash, resource, fileName);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							JOptionPane.showMessageDialog(getParent(), "Err: "+e1.getMessage());
						}
			            
			            if(bResult){
			            	JOptionPane.showMessageDialog(getParent(), "Ghi xuống FILE DAT thành công!!!", "Thông báo",
									JOptionPane.INFORMATION_MESSAGE);
			            }
			        }
                }
			}
		});
		btnGhiXuongFiles.setIcon(new ImageIcon(Luong.class.getResource("/images/save.png")));
		btnGhiXuongFiles.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnGhiXuongFiles);
		
		JButton btnDong = new JButton("Đóng[x]");
		btnDong.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
				
			}
		});
		btnDong.setIcon(new ImageIcon(Luong.class.getResource("/images/cancel.gif")));
		btnDong.setFont(new Font("Cambria", Font.PLAIN, 16));
		toolBar.add(btnDong);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 60, 808, 372);
		contentPane.add(scrollPane);
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				bFlag=true;
			}
		});
		table.setFillsViewportHeight(true);
		table.setColumnSelectionAllowed(true);
		table.setCellSelectionEnabled(true);
		scrollPane.setViewportView(table);
		LoadData(true);
	}
	 public void LoadData(boolean typeData) {
	        try {
	            // 1. Kiểm tra trạng thái kết nối
	            if (!m_objConnection.isClosed()) {
	                ResultSet objRS = null;
	                if (typeData) {
	                    // 2. Thực thi nhận v�? tập bản ghi Users
	                    if (m_objLuongController == null) {
	                        m_objLuongController = new LuongControllers(m_objConnection, m_objSecurityContext);
	                    }
	                    try {
	                        objRS = m_objLuongController.ExecOfGetElements();
	                    } catch (Exception e) {
	                        JOptionPane.showMessageDialog(getParent(), "Err: " + e, "Thông báo", JOptionPane.ERROR_MESSAGE);
	                    }
	                }
	                // 3. Khai báo khởi tạo đối tượng
	                Controls objControls = new Controls();

	                // 4. Thực thi phương thức getModels để nhận v�?
	                // DefaulTableModels
	                try {
	                    objDTM = objControls.getModels(objRS);
	                } catch (Exception e) {
	                    System.out.println(e.getMessage());
	                }
	                table.setModel(objDTM);

	                
	            } else {
	                JOptionPane.showMessageDialog(getParent(), "Không kết nối được với CSDL!", "Thông báo",
	                        JOptionPane.ERROR_MESSAGE);
	            }
	        } catch (SQLException ex) {
	            JOptionPane.showMessageDialog(getParent(), "Có lỗi xảy ra. Chi tiết: " + ex.getMessage(), "Thông báo",
	                    JOptionPane.ERROR_MESSAGE);
	        }
	    }
}
